package org.dromara.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.sql.*;
import java.util.*;

@Service
public class test {

    // 钉钉应用配置
    private static final String DINGTALK_APP_KEY = "dingu4kmt7ghr8sy3jye";
    private static final String DINGTALK_APP_SECRET = "S4p7LUxk0CH9WJY977h7k1s1EiXW7YTplYio0N1arcIEXiWNLvXLGwoGbsFNYVRM";
    private static final String APPROVAL_CODE = "PROC-F7867DB6-E7D9-4D5B-ADF1-48C07865968F"; // 审批模板唯一标识


    private static RestTemplate restTemplate = new RestTemplate();

    // 获取钉钉Access Token
    private static String getDingTalkAccessToken() {
        String url = "https://api.dingtalk.com/v1.0/oauth2/accessToken";
        Map<String, String> request = new HashMap<>();
        request.put("appKey", DINGTALK_APP_KEY);
        request.put("appSecret", DINGTALK_APP_SECRET);

        ResponseEntity<Map> response = restTemplate.postForEntity(url, request, Map.class);
        return (String) response.getBody().get("accessToken");
    }

    // 分页获取审核通过的审批实例
    private static List<Map<String, Object>> getApprovedInstances(String accessToken,Long page,Long maxResults) {
        String url = "https://api.dingtalk.com/v1.0/workflow/processes/instanceIds/query";
        HttpHeaders headers = new HttpHeaders();
        headers.set("x-acs-dingtalk-access-token", accessToken);

        Map<String, Object> request = new HashMap<>();
        request.put("processCode", APPROVAL_CODE);
//        request.put("statuses", "agree"); // 审核通过
        request.put("startTime", System.currentTimeMillis() - 24 * 60 * 60 * 100000); // 最近24小时
        request.put("nextToken", page); // 分页大小
        request.put("maxResults", maxResults); // 分页大小

        List<Map<String, Object>> instances = new ArrayList<>();
        while (true) {
//            request.put("cursor", page* 1);
            HttpEntity<Map> entity = new HttpEntity<>(request, headers);
            ResponseEntity<Map> response = restTemplate.exchange(url, HttpMethod.POST, entity, Map.class);
            Map<String, Object> result = response.getBody();

            Map<String, Object> resultMap = (Map<String, Object>) response.getBody().get("result");
           if( resultMap.get("nextToken") == null) break;
            instances.addAll((List)resultMap.get("list"));
            request.put("nextToken", resultMap.get("nextToken")); // 分页大小
        }
        return instances;
    }

    public static void main(String[] args) {
        String dingTalkAccessToken = getDingTalkAccessToken();
//        System.out.println(dingTalkAccessToken);
        List<Map<String, Object>> list =getApprovedInstances(dingTalkAccessToken,0l,10l);
//        System.out.println(System.currentTimeMillis() - 24 * 60 * 60 * 100000);
    }


}
